package com.hhd.pdf.component.dict;

import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.component.AbstractPdfComponent;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.utils.PdfUtils;
import com.hhd.pdf.variable.DynamicFormula;
import com.hhd.pdf.variable.VariableContext;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfDiv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DictComponent extends AbstractPdfComponent {
    @Autowired
    @Lazy
    List<DictParser> parserList;

    @Override
    public List<Element> doGenElements(GeneratorContext context) {
        DictParser dictParser = getDictParser(context.getParsingElement());
        Object formulaValue = getFormulaValue(context.getParsingElement(), context.getVariableContext());

        String value = dictParser.parseDict(formulaValue);

        Phrase phrase = new Phrase(value, context.getGeneratorParameters().getFont());

        return CommonUtils.newList(phrase);
    }

    @Override
    public List<Element> genElements(GeneratorContext context) {
        List<Element> res = doGenElements(context);
        if (CommonUtils.isEmpty(res)) return CommonUtils.newList();
        return res;
    }

    private DictParser getDictParser(org.dom4j.Element element) {
        String dictParserName = element.attributeValue("dictParser");
        if (CommonUtils.isEmpty(dictParserName)) dictParserName = "default";
        for (DictParser dictParser : parserList) {
            if (dictParser.getDictParserName().equals(dictParserName)) {
                return dictParser;
            }
        }
        throw new RuntimeException("没有找到数据字典解析器: " + dictParserName);
    }

    private static Object getFormulaValue(org.dom4j.Element element, VariableContext rootVariableContext) {
        String valueFormula = element.attributeValue("value");
        DynamicFormula<Object> formula = DynamicFormula.formula(valueFormula, Object.class);
        rootVariableContext.execute(formula);

        return formula.getFormulaValue();
    }

    @Override
    public String getName() {
        return "dict";
    }
}
